package com.epam.edu.task02.Strings.textParts;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.epam.edu.task02.Strings.ConfigurationRegex;

public class Text {
	private int numberOfSentences;
	private List<Sentence> sentences = new LinkedList<Sentence>();
	private ConfigurationRegex regex = new ConfigurationRegex();
	private Editor editor = new Editor();

	public Text(String text) {
		splitTextIntoSentence(text);
		setNumberofsentences();
	}

	public int getNumberofsentences() {
		return numberOfSentences;
	}

	public Sentence getSentence(int index) {
		return sentences.get(index);
	}

	public String getSentenceAsString(int index) {
		return sentences.get(index).toString();
	}

	public int getSentenceCount() {
		return sentences.size();
	}

	private void setNumberofsentences() {
		this.numberOfSentences = sentences.size();
	}

	public void setSentence(int index, Sentence sentence) {
		this.sentences.set(index, sentence);
	}

	public void sortByDescendingNumberOfWords() {
		Collections.sort(this.sentences, new SortedSentences());
	}

	private void splitTextIntoSentence(String text) {
		text = Editor.removeDoubleSpaceAndTab(text);
		String regex = ConfigurationRegex.getEndSentence();
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(text);
		int sentenceBegin = 0;
		while (matcher.find()) {
			int index = matcher.end();
			String substring = text.substring(sentenceBegin, index);
			Sentence newSentence = new Sentence(substring);
			sentences.add(newSentence);
			sentenceBegin = index + 1;
		}

	}

	@Override
	public String toString() {
		StringBuilder entireParagraph = new StringBuilder();
		for (Sentence sentence : sentences) {
			entireParagraph.append(sentence + " ");
		}
		return entireParagraph.toString();
	}

}
